package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.bean.User;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.解决请求和响应中文乱码
         req.setCharacterEncoding("utf-8");
         resp.setContentType("application/json;charset=utf-8");

        //2.获取请求参数username
        String username = req.getParameter("username");

        //3.调用service层方法,查询结果
        UserServiceImpl userService= new UserServiceImpl();
        List<User> list = userService.findByUsername(username);

        //4.将结果转换成json响应给客户端
        ObjectMapper objectMapper= new ObjectMapper();
        objectMapper.writeValue(resp.getWriter(), list);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
